<script lang="ts" setup>
import { ref, h, reactive, onMounted,onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton,VxeCheckbox,VxeImage } from "vxe-pc-ui";
import { ElMessage } from "element-plus";
import { exportFile } from '@/api/export';
import { downloadFile } from '@/api/file';
import { baseUrlApi } from "@/api/utils";
import recordDetail from "./components/recordDetail.vue";
import { invoiceOrderState,invoiceList } from "@/api/invoice/invoice";
import {
  MerchantsInfoByTaxSourcesId,
} from "@/api/welcome";
import { useRouter } from "vue-router";
const router = useRouter();
const reVxeGridRef = ref();
let taxSourcesId = Number(sessionStorage.getItem("taxSourcesId"))
onMounted(() => {
  //开票状态
  getstate()
  getMerchantsInfoByTaxSourcesId( taxSourcesId )
});
interface RestaurantItem {
  id: number
  value: string
}
const listMerchantsInfoByTaxSourcesId = ref<RestaurantItem[]>([]);
const getMerchantsInfoByTaxSourcesId = (taxSourcesId?:
  number): void => {
  MerchantsInfoByTaxSourcesId(taxSourcesId).then((res: any) => {
    listMerchantsInfoByTaxSourcesId.value = res.data;
  });
};
// 开票状态
const stateOptions = ref<any[]>();
const getstate = () => {
  invoiceOrderState().then((res: any) => {
    stateOptions.value = res.data;
  });
};
// 根据税源地ID查询合作公司列表搜索
const fetchSuggestions = (queryString: any, cb: (params: any) => void) => { 
  const results = queryString
    ? listMerchantsInfoByTaxSourcesId.value.filter(createFilter(queryString))
    : listMerchantsInfoByTaxSourcesId.value  
    cb(results)
  
};
const createFilter = (queryString: string) => {
  return (listMerchantsInfoByTaxSourcesId: RestaurantItem) => {
    return (
      listMerchantsInfoByTaxSourcesId.value.indexOf(queryString) === 0
    )
  }
}
const autoselect = (res: any) => {
  console.log(res);
  formOptions.data.merchantsName = res.value;
};

const columns: VxeGridPropTypes.Columns<any> = [
  {
    title: "申请企业",
    field: "merchantsName",
    align: "center",
    minWidth: 100,
    showOverflow: true
  },
  {
    title: "业务公司",
    field: "taxSourcesIdDisplay",
    align: "center",
    minWidth: 100,    
  }, 
  {
    title: "开票金额",
    field: "amountOfApply",
    align: "center",
    minWidth: 100,    
  }, 
  {
    title: "开票类型",
    field: "invoiceTypeDisplay",
    align: "center",
    minWidth: 60,    
  }, 
  {
    title: "审核状态",
    field: "invoiceOrderStateDisplay",
    align: "center",
    minWidth: 60,    
  }, 
  {
    title: "申请时间",
    field: "createTime",
    align: "center",
    minWidth: 60,    
  },   
  {
    title: "操作",
    field: "operate",
    align: "center",
    minWidth: 140,
    slots: {
      default: ({ row }) => {
        return [
          h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "开票信息",
              onClick() {
                recordDetailRef.value.showAddModal(row.id);              
              }
            }),h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "查看票据",
              onClick() {
                toexport(row.id)
              }
            })
          ]
      }
    }
  }
   
];
const toexport = (id) => {
  // exportFile
  exportFile(baseUrlApi(`business/project_task/listProjectTaskExportTax/${id}`))
}
// 查看票据信息

const recordDetailRef = ref();
// 筛选相关
const formRef = ref();
interface FormDataVO {
  merchantsName: string;//公司名称
  taxSourcesId: number | string; // 税源地 
  createTimeStart: number | string; //开始日期
  createTimeEnd: number | string; //结束日期
  invoiceOrderState: string
  
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    merchantsName: '',
    taxSourcesId: taxSourcesId, 
    createTimeStart: "",
    createTimeEnd: "", 
    invoiceOrderState:''
  },
  items: [
    {
      field: "merchantsName",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsName" }
    },  
    {
      field: "invoiceOrderState",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "invoiceOrderState" }
    },
    {
      field: "timeRang",
      title: "",
      span: 6,
      itemRender: {},
      slots: { default: "timeRang" }
    },   
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});
// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    taxSourcesId: '',
    merchantsName: '',
    createTimeStart: "",
    createTimeEnd: "",
    timeRang: [],
    invoiceOrderState:''
  };
};
const handleSearch = () => {
  if (formOptions.data?.timeRang?.length) {
    formOptions.data.createTimeStart = formOptions.data.timeRang[0];
    formOptions.data.createTimeEnd = formOptions.data.timeRang[1];
    delete formOptions.data.timeRang;
  }
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

const handleView = (record: Recordable) => {
  
};
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};
const checkedData = async (data: any) => {
  // if (data.length == 0) {
  //   ElMessage.error("请选择！");
  //   return false;
  // }
  let obj = {
    projectTaskDtlId: [],
    projectTaskId: formOptions.data.projectTaskId,
    type: 1
  }
  downloadFile(baseUrlApi("business/project_task_dtl/projectBatchDownload"), obj,'post')
};

</script>
<template>
  <div>
    <el-card :shadow="`never`">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #merchantsName="{ data }">
          <el-autocomplete
            clearable
            v-model="data.merchantsName"
            :fetch-suggestions="fetchSuggestions"
            placeholder="请输入公司名称"
            value-key="value"
            @select="autoselect"
          >
          </el-autocomplete>
        </template> 
        <template #invoiceOrderState="{ data }">
          <el-select
            clearable
            placeholder="请选择开票状态"
            v-model="data.invoiceOrderState"
          >
            <el-option
              v-for="(item, index) in stateOptions"
              :key="index"
              :label="item.desc"
              :value="item.code"
            ></el-option>
          </el-select>
        </template>
        <template #timeRang="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.timeRang"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </template>     
        <template #active>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >搜索</el-button
          >
          <el-button @click="handleReset" native-type="reset">重置</el-button>          
        </template>
      </vxe-form>
    </el-card>
    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="invoiceList"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"
        @handleView="handleView"
         @checkedData="checkedData"
      />
    </el-card>
    <recordDetail ref="recordDetailRef" @reload="handleSearch" />
  </div>
</template>
<style>
</style>
